package com.atwulidun.sparsearray;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;

public class SparseArray {
    public static void main(String[] args) {
        // 创建一个二维数组arr1
        int[][] arr1 = new int[11][11];
        arr1[1][2] = 1;
        arr1[2][3] = 2;
        arr1[3][4] = 1;
        for (int[] ints : arr1) {
            for (int anInt : ints) {
                System.out.printf("%d\t",anInt);
            }
            System.out.println();
        }
        // 将二维数组arr1转换为稀疏数组
        int sum = 0;
        for (int[] ints : arr1) {
            for (int anInt : ints) {
                if (anInt != 0) {
                    sum++;
                }
            }
        }
        int[][] sparseArr = new int[sum+1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;
        int count = 0;
        for (int i = 0; i < arr1.length; i++) {
            for (int j = 0; j < arr1[i].length; j++) {
                if (arr1[i][j] != 0) {
                    ++count;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = arr1[i][j];
                }
            }
        }
        for (int[] ints : sparseArr) {
            System.out.printf("%d\t%d\t%d\t",ints[0],ints[1],ints[2]);
            System.out.println();
        }
        // 将稀疏数组写入到硬盘中
        try (FileOutputStream fileOutputStream = new FileOutputStream(
                "E:\\sparseArray\\sparseArray");
             ObjectOutputStream outputStream = new ObjectOutputStream(fileOutputStream);
        ) {
            outputStream.writeObject(sparseArr);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
